package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.common.StatusCode;
import com.example.demo.model.Comment;
import com.example.demo.model.Dishes;
import com.example.demo.service.AuthService;
import com.example.demo.service.CommentService;
import com.example.demo.service.DishesService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("/dishes")
public class DishesController {
    @Autowired
    private  DishesService dishesService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private AuthService authService;

    @GetMapping
    public ResponseEntity<Result<List<Dishes>>> getAllDishes() {
        List<Dishes> dishes = dishesService.getAllDishes();
        return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "查询成功", dishes));
    }

    @PostMapping("/recognizeFood")
    public ResponseEntity<String> recognizeFood(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("上传的文件为空");
            }

            // 获取文件名
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            System.out.println("上传的文件名：" + fileName);

            // 指定保存的文件路径和文件名
            String uploadDir = "E:/ressource/file/identity/";
            File uploadDirFile = new File(uploadDir);
            if (!uploadDirFile.exists()) {
                uploadDirFile.mkdirs(); // 创建文件夹
            }
            String filePath = uploadDir + fileName;

            // 保存文件
            File dest = new File(filePath);
            file.transferTo(dest);

            // 获取文件后缀
            String tail = fileName.substring(fileName.lastIndexOf("."));

            // 在这里进行文件处理逻辑
            Dishes dishes = dishesService.recognizeFood(filePath);
//            dishesService.add(dishes);
            System.out.println(dishes);

            if (dishes != null) {
                // 如果成功识别食品，构建包含食品信息的 map 对象
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("name", dishes.getName());
                dataMap.put("description", dishes.getDescription());
                dataMap.put("image", dishes.getImage());

                // 构建包含食品信息的 jsonResponse 字符串
                ObjectMapper objectMapper = new ObjectMapper();
                String jsonResponse = objectMapper.writeValueAsString(new HashMap<String, Object>() {{
                    put("success", true);
                    put("code", 200);
                    put("message", "查询成功");
                    put("data", dataMap);
                }});

                System.out.println(jsonResponse);
                return ResponseEntity.ok(jsonResponse);
            } else {
                // 如果未能识别食品，返回状态码404
                String jsonResponse = "{\"success\":false,\"code\":404,\"message\":\"未能识别食品\"}";

                return ResponseEntity.ok(jsonResponse);
            }
        } catch (IOException  e) {
            e.printStackTrace();
            // 处理异常，例如返回500错误状态码
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


    @GetMapping("/viewDishById/{dishId}")
    public ResponseEntity<Result<Dishes>> getDishesById(@PathVariable Long dishId) {
        Dishes dish = dishesService.getDishesById(dishId);
        if (dish != null) {
            return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "查询成功", dish)); // 如果找到了对应的菜品，返回状态码200和菜品信息
        } else {
            return ResponseEntity.ok(new Result<>(false, StatusCode.ERROR, "未找到对应的菜品", null)); // 如果未找到对应的菜品，返回状态码404
        }
    }

    @PostMapping("/view/{name}/{dishId}")
    public ResponseEntity<Result<String>> viewDish(@PathVariable String name, @PathVariable Long dishId) {
        dishesService.incrementDishViewCount(dishId);
//        authService.addViewDishToUser(name, dishId);
        return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "Dish view count updated successfully", null));
    }

    @GetMapping("/classified")
    public ResponseEntity<Result<Map<String, List<Dishes>>>> getClassifiedDishes() {
        Map<String, List<Dishes>> classifiedDishes = dishesService.classifyDishesByIngredient();
        System.out.println(classifiedDishes);
        return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "查询成功", classifiedDishes));
    }

    @GetMapping("/search/{name}")
    public ResponseEntity<Result<List<Dishes>>> searchDishesByIngredient(@PathVariable String name) {
        System.out.println(name);
        List<Dishes> foundDishes = dishesService.getDishesByIngredientName(name);
        System.out.println(foundDishes);
        return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "查询成功", foundDishes));
    }


    @GetMapping("/RecoommandForUserInfo/{description}")
    public ResponseEntity<Result<List<Dishes>>> RecommandForUserInfo(@PathVariable String description) {
        // 对用户的自然语言进行处理
        List<Dishes> recommandFood = dishesService.RecommandForUserInfo(description);
        return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "查询成功", recommandFood));
    }

    //根据id查询评论信息
    @GetMapping("/selectCommentsByDishId/{id}")
    public Result selectCommentsByDishId(@PathVariable("id") Long id){
        List<Comment> comments = commentService.selectByDishId(id);
        return new Result(true,StatusCode.OK,"查询成功",comments);
    }

    //添加评论
    @PostMapping("/addComment/{id}/{ownName}/{content}")
    public Result addComment(@PathVariable("id") Integer id,
                             @PathVariable("ownName") String ownName,
                             @PathVariable("content") String content){
        System.out.println(ownName);
        System.out.println(content);
        //获取登录的用户名
        Comment comment = new Comment();
        comment.setDishId(id);
        comment.setOwnName(ownName);
        comment.setCreateTime(new Date());
        comment.setContent(content);

        commentService.add(comment);
        return new Result(true,StatusCode.OK,"评论成功",comment);
    }

}
